﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CreateCodeByDatabase.Model
{
    /// <summary>
    /// 系统日志表
    /// </summary>
    public class Log
    {
        /// <summary>
        /// 操作时间
        /// </summary>
        public DateTime CreateTime { get; set; }
        /// <summary>
        /// 类型
        /// </summary>
        public string Type { get; set; }
        /// <summary>
        /// 标题
        /// </summary>
        public string Title { get; set; }
        /// <summary>
        /// 内容
        /// </summary>
        public string Content { get; set; }
        public static void WriteLog(string logInfo)
        {
            Log log = new Log();
            log.Title = logInfo;
            log.Type = enumLogType.操作日志.ToString();
            log.CreateTime = DateTime.Now;
            WritLog(log);
        }
        public static void WriteLog(string title, Exception ex)
        {
            Log log = new Log();
            log.Title = title;
            log.Content = ex.Message + Environment.NewLine + ex.StackTrace;
            log.Type = enumLogType.错误日志.ToString();
            log.CreateTime = DateTime.Now;
            WritLog(log);
        }
        public static void WriteLog(Exception ex)
        {
            Log log = new Log();
            log.Title = ex.Message;
            log.Content = ex.StackTrace;
            log.Type = enumLogType.异常日志.ToString();
            log.CreateTime = DateTime.Now;
            WritLog(log);
        }
        private static void WritLog(Log log,bool repeat = true)
        {
            string tempPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs");
            if (!Directory.Exists(tempPath))
                Directory.CreateDirectory(tempPath);
            tempPath = Path.Combine(tempPath, DateTime.Now.ToString("yyyy-MM-dd") + ".txt");
            try
            {
                using (StreamWriter sw = File.AppendText(tempPath))
                {
                    sw.WriteLine("时间:" + log.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"));
                    sw.WriteLine("标题:" + log.Title);
                    sw.WriteLine("类型:" + log.Type);
                    if( !string.IsNullOrWhiteSpace(log.Content) )
                        sw.WriteLine("内容:" + log.Content);
                    sw.WriteLine("");
                    sw.Flush();
                }
            }
            catch (Exception ex)
            {
                if (!repeat)
                    return;
                Log logModel = new Log();
                logModel.Title = ex.Message;
                logModel.Content = ex.StackTrace;
                logModel.Type = enumLogType.异常日志.ToString();
                logModel.CreateTime = DateTime.Now;
                WritLog(logModel, false);
            }
        }
    }
}
